package com.example.choupaiapp.common.ui.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.choupaiapp.R;
import com.example.choupaiapp.common.finalokgo.request.FinalOkgo;
import com.example.choupaiapp.common.util.ActivityManager;
import com.example.choupaiapp.common.util.Utils;
import com.gyf.immersionbar.ImmersionBar;
import com.orhanobut.logger.Logger;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.umeng.analytics.MobclickAgent;

import butterknife.ButterKnife;
import cn.jpush.android.api.JPushInterface;


/**
 * Created by ASUS on 2018/2/6.
 */

public abstract class CommonActivity extends AppCompatActivity {
    private TextView title;
    private View back;
    protected Dialog loadingDialog;
    protected FinalOkgo finalOkGo;
    protected RxPermissions rxPermissions;
    protected Context context;
    protected RelativeLayout empty;
    private Toast toast;
    private View toastview;
    private boolean isAnimate = true;

    @SuppressWarnings("unchecked")
    public <T extends View> T findView(int id) {
        return (T) findViewById(id);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setAllowEnterTransitionOverlap(true);
            getWindow().setAllowReturnTransitionOverlap(true);
        }
        if (rxPermissions == null) {
            rxPermissions = new RxPermissions(this);
        }
        if (finalOkGo == null) {
            finalOkGo = new FinalOkgo(this);
        }
        context = this;

        if (isAnimate) {
            overridePendingTransition(R.anim.slide_in_right, R.anim.no_slide);
        }
    }

    protected void setAnimate(boolean isAnimate){
        this.isAnimate = isAnimate;
    }

    @Override
    public Resources getResources() {//还原字体大小
        Resources res = super.getResources();
        Configuration configuration = res.getConfiguration();
        if (configuration.fontScale != 1.0f) {
            configuration.fontScale = 1.0f;
            res.updateConfiguration(configuration, res.getDisplayMetrics());
        }
        return res;
    }

    @Override
    protected void onPause() {
        super.onPause();
        JPushInterface.onPause(this);
        MobclickAgent.onPause(this);
        ActivityManager.getActivityManager().pushActivity(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        JPushInterface.onResume(this);
        MobclickAgent.onResume(this);
        ActivityManager.getActivityManager().popActivity(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        ImmersionBar.with(this).statusBarDarkFont(true, 0.2f).init();
        super.setContentView(layoutResID);
        ButterKnife.bind(this);
        init();
    }

    @Override
    public void setContentView(View view) {
        ImmersionBar.with(this).statusBarDarkFont(true, 0.2f).init();
        super.setContentView(view);
        ButterKnife.bind(this);
        init();
    }

    @Override
    public void setContentView(View view, ViewGroup.LayoutParams params) {
        ImmersionBar.with(this).statusBarDarkFont(true, 0.2f).init();
        super.setContentView(view, params);
        ButterKnife.bind(this);
        init();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void finish() {
        super.finish();
        if (isAnimate) {
            overridePendingTransition(R.anim.no_slide, R.anim.slide_out_right);
        }
    }


    @Override
    public void finishAfterTransition() {
        super.finishAfterTransition();
        if (isAnimate) {
            overridePendingTransition(R.anim.no_slide, R.anim.slide_out_right);
        }
    }

    /**
     * 启动activity
     *
     * @param cls
     * @param bundle
     */
    public void startActivityCompat(Class<?> cls, @Nullable Bundle bundle) {
        Intent intent = new Intent(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        ActivityCompat.startActivity(this, intent, ActivityOptionsCompat.makeSceneTransitionAnimation(this).toBundle());
    }

    public void startActivity(Class<?> cls, @Nullable Bundle bundle) {
        Intent intent = new Intent(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    public void startActivityCompat(Class<?> cls) {
        Intent intent = new Intent(this, cls);
        ActivityCompat.startActivity(this, intent, ActivityOptionsCompat.makeSceneTransitionAnimation(this).toBundle());
    }

    public void startActivity(Class<?> cls) {
        Intent intent = new Intent(this, cls);
        startActivity(intent);
    }

    public void startFinishActivity(Class<?> cls) {
        Intent intent = new Intent(this, cls);
        startActivity(intent);
        finish();
    }

    public void startFinishActivity(Class<?> cls, @Nullable Bundle bundle) {
        Intent intent = new Intent(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
        finish();
    }

    public void finishActivity() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            finishAfterTransition();
        } else {
            finish();
        }
    }

    public void call(String phoneStr) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneStr));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }


    private void init() {
        back = findView(R.id.back);
        if (back != null) {
            back.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finishActivity();
                }
            });
        }
        title = (TextView) findView(R.id.title);
        empty = findView(R.id.empty);
        if (empty != null) {
            empty.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    initData();
                }
            });
        }

//        initView();
//        initData();
        try {
            initView();
            initData();
        } catch (Exception e) {
            e.printStackTrace();
            Logger.e(e.getMessage());
        }
    }

    protected abstract void initView();

    protected abstract void initData();

    protected void setTitle(String titleStr) {
        if (title != null) {
            title.setText(titleStr);
        }
    }

    /**
     * @param context
     * @param msg     这个不填也行，默认是加载中...
     */
    public void showDialog(Context context, @Nullable String msg) {
//        LayoutInflater inflater = LayoutInflater.from(context);
//        View v = inflater.inflate(R.layout.dialog_loading, null);// 得到加载view
//        LinearLayout layout = (LinearLayout) v
//                .findViewById(R.id.dialog_loading_view);// 加载布局
//        TextView tipTextView = (TextView) v.findViewById(R.id.tipTextView);// 提示文字
//        if (TextUtils.isEmpty(msg)) {
//            tipTextView.setText("加载中...");//
//        } else {
//            tipTextView.setText(msg);// 设置加载信息
//        }
//
//
//        loadingDialog = new Dialog(context, R.style.MyDialogStyle);// 创建自定义样式dialog
//        loadingDialog.setCancelable(true); // 是否可以按“返回键”消失
//        loadingDialog.setCanceledOnTouchOutside(true); // 点击加载框以外的区域
//        loadingDialog.setContentView(layout, new LinearLayout.LayoutParams(
//                LinearLayout.LayoutParams.MATCH_PARENT,
//                LinearLayout.LayoutParams.MATCH_PARENT));// 设置布局
//        /**
//         *将显示Dialog的方法封装在这里面
//         */
//        Window window = loadingDialog.getWindow();
//        WindowManager.LayoutParams lp = window.getAttributes();
//        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
//        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
//        window.setGravity(Gravity.CENTER);
//        window.setAttributes(lp);
//        window.setWindowAnimations(R.style.PopWindowAnimStyle);
//        if (isValidContext(context)) {
//            loadingDialog.show();
//        }
    }

    /**
     * 关闭dialog
     */
    public void dismissDialog() {
        if (loadingDialog != null && loadingDialog.isShowing() && isValidContext(this)) {
            loadingDialog.dismiss();
        }
    }


    private boolean isValidContext(Context c) {

        Activity a = (Activity) c;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            if (a.isDestroyed() || a.isFinishing()) {
                return false;
            } else {
                return true;
            }
        } else {
            if (a.isFinishing()) {
                return false;
            } else {
                return true;
            }
        }
    }

    public void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    public void showLongToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }

    public void showImageToas(String message) {
        if (toastview == null) {
            toastview = LayoutInflater.from(this).inflate(R.layout.toast_image_layout, null);
        }
        TextView tipTextView = (TextView) toastview.findViewById(R.id.tipTextView);
        tipTextView.setText(message);    //要提示的文本
        //上下文
        if (toast == null) {
            toast = new Toast(this);
        }
        toast.setGravity(Gravity.TOP | Gravity.FILL_HORIZONTAL, 0, 0);   //位置居中
        toast.setDuration(Toast.LENGTH_SHORT);  //设置短暂提示
        toast.setView(toastview);   //把定义好的View布局设置到Toast里面
        toast.show();

        toastview.setOnClickListener(view -> toast.cancel());
    }

    public String getAppVersionName() {
        try {
            PackageInfo Info = getPackageManager().getPackageInfo(getPackageName(), 0);
            return Info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return "";
    }

    public int getAppVersionCode() {
        try {
            PackageInfo Info = getPackageManager().getPackageInfo(getPackageName(), 0);
            return Info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return 0;
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                View view = getCurrentFocus();
                Utils.hideKeyboard(ev, view, this);//调用方法判断是否需要隐藏键盘
//                break;
            default:
                break;
        }
        return super.dispatchTouchEvent(ev);

    }

//    @OnClick({})
//    public void onViewClicked(View view) {
//        if (Utils.isDoubleClick()) {
//            return;
//        }
//    }

}
